<template>
    <n-data-table
        :columns="config.columns"
        :loading="loading"
        :data="data?.data || []"
        :pagination="paginationReactive"
        remote
        :row-key="(rowData: any) => rowData.id"
        :bordered="false"
    />
</template>

<script setup lang="ts">
import { onMounted, PropType, reactive } from 'vue'
import { TablePaginationConfig } from '../types'
import { usePagination } from 'vue-request'
import { PaginationProps, useMessage } from 'naive-ui'
import { IPageListParameter } from '@/types/global'

type DataType = any

const props = defineProps({
    config: {
        type: Object as PropType<TablePaginationConfig<DataType>>,
        required: true
    }
})

const message = useMessage()

// 默认请求参数
const defaultParams: IPageListParameter = {
    page: 1,
    limit: 10
}

// 执行请求
function runService(params?: object) {
    run(
        Object.assign(
            {},
            {
                page: paginationReactive.page,
                limit: paginationReactive.pageSize
            },
            props.config?.params || {},
            params || {}
        )
    )
}

// 分页
const paginationReactive = reactive<PaginationProps>({
    page: defaultParams.page,
    pageSize: defaultParams.limit,
    pageCount: 1,
    showSizePicker: true,
    showQuickJumper: true,
    showQuickJumpDropdown: true,
    pageSizes: [10, 20, 50, 100],
    onUpdatePage: function (page) {
        paginationReactive.page = page
        runService()
    },
    onUpdatePageSize: function (size) {
        paginationReactive.page = 1
        paginationReactive.pageSize = size
        runService()
    }
})

// 请求数据
const { loading, data, run } = usePagination(props.config.service, {
    manual: true,
    onError(error) {
        message.error(error.message)
    },
    onSuccess(res) {
        paginationReactive.page = res.current_page
        paginationReactive.pageSize = res.per_page
        paginationReactive.pageCount = res.last_page
    }
})

onMounted(() => {
    const auto = props.config.auto
    if (typeof auto === 'undefined' || auto === true) {
        run({
            ...defaultParams,
            ...(props.config?.params || {})
        })
    }
})

defineExpose({
    run: runService
})
</script>
